package 实验四5;

class SumTask implements Runnable {
    private final int[] array;
    private final int start;
    private final int end;
    private int sum;

    public SumTask(int[] array, int start, int end) {
        this.array = array;
        this.start = start;
        this.end = end;
    }

    @Override
    public void run() {
        sum = 0;
        for (int i = start; i < end; i++) {
            sum += array[i];
        }
    }

    public int getSum() {
        return sum;
    }
}

public class Main {
    public static void main(String[] args) throws InterruptedException {
        // 创建示例数组
        int[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        int mid = array.length / 2;

        // 创建两个任务，分别计算前半部分和后半部分
        SumTask task1 = new SumTask(array, 0, mid);
        SumTask task2 = new SumTask(array, mid, array.length);

        // 创建并启动线程
        Thread thread1 = new Thread(task1);
        Thread thread2 = new Thread(task2);
        thread1.start();
        thread2.start();

        // 等待两个线程执行完毕
        thread1.join();
        thread2.join();

        // 汇总结果
        int totalSum = task1.getSum() + task2.getSum();
        System.out.println("数组总和: " + totalSum);
    }
}
